﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Kelper.Infrastructure.Abstract;

namespace Kelper.Infrastructure.Filters
{
    public class LoginAttribute : ActionFilterAttribute
    {
        public Func<HttpContextBase, IAccountManager> GetAccountManager { get; set; }

        public LoginAttribute()
        {
            GetAccountManager = context => new SessionAccountManager(context.Session);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IAccountManager accounts = GetAccountManager(filterContext.HttpContext);

            if (!accounts.IsLoggedIn())
            {
                UrlHelper url = new UrlHelper(filterContext.RequestContext);
                filterContext.Result = new RedirectResult(url.Action("login", "user",
                    new { target = Uri.EscapeUriString(filterContext.HttpContext.Request.Url.ToString()) }));
            }
        }
    }
}